package io.jpress.module.article.service.provider;

import com.github.houbb.heaven.util.lang.StringUtil;
import io.jboot.Jboot;
import io.jboot.aop.annotation.Bean;
import io.jboot.components.cache.annotation.Cacheable;
import io.jboot.db.model.Column;
import io.jboot.db.model.Columns;
import io.jpress.commons.service.JPressServiceBase;
import io.jpress.module.article.model.ArticleImage;
import io.jpress.module.article.service.ArticleImageService;

import java.util.Comparator;
import java.util.List;

@Bean
public class ArticleImageServiceProvider extends JPressServiceBase<ArticleImage> implements ArticleImageService {

    private static final String cacheName = "articleImage";


    @Override
    @Cacheable(name = cacheName, key = "articleId:#(articleId)", nullCacheEnable = true)
    public List<ArticleImage> findListByArticleId(Long articleId) {
        List<ArticleImage> list = DAO.findListByColumn(Column.create("article_id", articleId));
        if (list != null && !list.isEmpty()) {
            list.sort(Comparator.comparingInt(ArticleImage::getOrderNumber));
        }
        return list == null || list.isEmpty() ? null : list;
    }

    @Override
    public void saveOrUpdateByArticleId(Long articleId, String src, int orderNumber) {
        ArticleImage image = DAO.findFirstByColumns(
                Columns.create("article_id", articleId)
                        .eq("order_number", orderNumber)
        );

        //删除图片
        if (StringUtil.isBlank(src)) {
            if (image != null) {
                delete(image);
            } else {
                return;
            }
        }
        // 用户设置了图片
        else {
            if (image == null) {
                image = new ArticleImage();
                image.setArticleId(articleId);
                image.setOrderNumber(orderNumber);
            }
            //用户设置了相同的图片
            else if (src.equals(image.getSrc())) {
                return;
            }
            image.setSrc(src);
            saveOrUpdate(image);
        }

        Jboot.getCache().remove(cacheName, "articleId:" + articleId);
    }


    @Override
    public boolean deleteByArticleId(Long articleId) {
        return DAO.deleteByColumn(Column.create("article_id", articleId));
    }
}